<?php

namespace src\common;

class Response
{
    public static function json($data, $code = 200, $msg = 'success')
    {
        header('Content-Type: application/json; charset=utf-8');
        self::accessControl();
        http_response_code($code);
        echo json_encode([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ]);
    }

    public static function text($data, $code = 200)
    {
        header('Content-Type: text/plain; charset=utf-8');
        self::accessControl();
        http_response_code($code);
        echo $data;
    }

    public static function err($message, $code = 500)
    {
        self::json(null, $code, $message);
        exit;
    }

    /**
     * 处理CORS跨域请求
     */
    private static function accessControl()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
    }
}